from PySide6.QtCore import Qt, Slot
from PySide6.QtGui import QIcon, QKeyEvent
from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QSizePolicy, QApplication

from keyboard import KeyButton, AbstractKeyboard
from keyboard.key_button import Mode


class NumberKeyboard(AbstractKeyboard):
  def __init__(self, parent=None):
    super().__init__(parent)
    layout = QVBoxLayout(self)
    layout.setSpacing(0)
    layout.setContentsMargins(0, 0, 0, 0)
    self.setStyleSheet('''
            QWidget {
                background-color: #2B2D30;
            }
        ''')

    def createLayout(mode_list):
      h_layout = QHBoxLayout()
      h_layout.setContentsMargins(0, 0, 0, 0)

      for modes in mode_list:
        button = self.createButton(modes)
        h_layout.addWidget(button)

      layout.addLayout(h_layout)

    # 定义按钮行
    mode_list_bar1 = [
      [Mode(key=Qt.Key_1, value='1')],
      [Mode(key=Qt.Key_2, value='2')],
      [Mode(key=Qt.Key_3, value='3')],
      [Mode(key=Qt.Key_Backspace, value='', display=QIcon("./assets/Image/backspace.png"))],
    ]

    mode_list_bar2 = [
      [Mode(key=Qt.Key_4, value='4')],
      [Mode(key=Qt.Key_5, value='5')],
      [Mode(key=Qt.Key_6, value='6')],
      [Mode(key=Qt.Key_Escape, value='', display=QIcon("./assets/Image/pack_up.png"))],
    ]

    mode_list_bar3 = [
      [Mode(key=Qt.Key_7, value='7')],
      [Mode(key=Qt.Key_8, value='8')],
      [Mode(key=Qt.Key_9, value='9')],
      [Mode(key=Qt.Key_Minus, value=',')],
    ]

    mode_list_bar4 = [
      [Mode(key=Qt.Key_unknown, value='.')],
      [Mode(key=Qt.Key_0, value='0')],
      [Mode(key=Qt.Key_Space, value=' ', display=QIcon("./assets/Image/space.png"))],
      [Mode(key=Qt.Key_unknown, value=':')],
    ]

    # 创建按钮布局，按行
    createLayout(mode_list_bar1)
    createLayout(mode_list_bar2)
    createLayout(mode_list_bar3)
    createLayout(mode_list_bar4)

    self.setLayout(layout)

  def createButton(self, modes):
    button = KeyButton(modes, self)
    button.pressed.connect(self.onButtonPressed)
    button.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
    return button

  @Slot(int, str)
  def onButtonPressed(self, code, text):
    print(f"Button pressed with code: {code}, text: '{text}'")
    self.onKeyPressed(code, text)

  def onKeyPressed(self, code, text):
    # 将按键事件转发到焦点组件
    receiver = QApplication.focusWidget()
    if receiver is not None:
      key_press = QKeyEvent(QKeyEvent.KeyPress, code, Qt.NoModifier, text)
      key_release = QKeyEvent(QKeyEvent.KeyRelease, code, Qt.NoModifier, text)
      QApplication.sendEvent(receiver, key_press)
      QApplication.sendEvent(receiver, key_release)